package com.lujianfei.filesend.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.lujianfei.filesend.MyApplication
import com.lujianfei.filesend.db.dao.TransferFileDao
import com.lujianfei.filesend.db.model.TransferFile

@Database(
    entities = [TransferFile::class],
    version = 1, exportSchema = true,
)
abstract class AppDataBase : RoomDatabase() {

    abstract fun transferFileDao(): TransferFileDao

    companion object {
        @Volatile
        private var instance: AppDataBase? = null

        fun getInstance(): AppDataBase =
            instance ?: synchronized(this) {
                instance ?: buildDataBase(MyApplication.instance)
                    .also {
                        instance = it
                    }
            }


        private fun buildDataBase(
            context: Context,
            dbName: String = "filesend-database"
        ): AppDataBase {
            return Room.databaseBuilder(context, AppDataBase::class.java, dbName)
                .addCallback(object : Callback() {
                })
                .fallbackToDestructiveMigration()
                .build()
        }
    }
}